import pygame
from pygame.sprite import Group
from pygame.sprite import Sprite
from settings import Settings
from ship import Ship
import game_functions as gf
from alien import Alien
from bullet import Bullet
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard

def run_game():
   
    ai_settings = Settings()     

    pygame.mixer.init()
    pygame.mixer.music.load(ai_settings.bg_music)#加载MP3文件
    pygame.mixer.music.set_volume(ai_settings.load)
    pygame.mixer.music.play(-1,0)#循环播放mp3文件                                # 初始化背景设置
    screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height))   # 创建一个名为screen的显示窗口
    background = pygame.image.load(ai_settings.background).convert_alpha()
    background.set_alpha(256)

    pygame.display.set_caption("Alien Invasion") 

    # 创建Play按钮
    play_button = Button(ai_settings, screen, "Play") 

    # 创建存储游戏统计信息的实例，并创建记分牌
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats) 

    # 创建一艘飞船
    ship = Ship(ai_settings, screen)

    # 创建一个用于存储子弹的编组
    bullets = Group() 

    # 创建外星人群
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens) 
 
    # 开始游戏的主循环    
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
            aliens, bullets)                                                     # 捕捉事件
        if stats.game_active:                                                    # 如果游戏处于活动状态
            ship.update()                                                        # 更新飞船
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                bullets)                                                         # 更新子弹
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                bullets)                                                         # 更新外星人 
        gf.update_screen(ai_settings,background, screen, stats, sb, ship, aliens,
            bullets, play_button)                                                # 屏幕展示结果
 
run_game()                                                                       # 初始化游戏并开始主循环
 